package com.hscy.push.service.impl;

import com.corundumstudio.socketio.SocketIOServer;
import com.hscy.push.util.ClientCacheUtil;
import com.hscy.push.listenner.EventListenner;
import com.hscy.push.service.SocketIOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.UUID;


@Slf4j
@Service(value = "socketIOService")
public class SocketIOServiceImpl implements SocketIOService {

    @Resource
    private SocketIOServer socketIOServer;
    @Resource
    private EventListenner eventListenner;

    /**
     * Spring IoC容器创建之后，在加载SocketIOServiceImpl Bean之后启动
     *
     * @throws Exception
     */
    @PostConstruct
    private void autoStartup() {
        start();
    }

    /**
     * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
     *
     * @throws Exception
     */
    @PreDestroy
    private void autoStop() {
        stop();
    }

    @Override
    public void start() {
        // 监听客户端连接
        socketIOServer.addConnectListener(client -> {
            String userId = client.getHandshakeData().getSingleUrlParam("userId");
            UUID sessionId = client.getSessionId();
            ClientCacheUtil.saveClient(userId, sessionId, client);
            log.info("sessionId:{}", sessionId);
            log.info("用户：{}建立连接！", userId);
        });

        // 监听客户端断开连接
        socketIOServer.addDisconnectListener(client -> {
            String userId = client.getHandshakeData().getSingleUrlParam("userId");
            UUID sessionId = client.getSessionId();
            ClientCacheUtil.deleteSessionClient(userId, sessionId);
            log.info("sessionId:关闭连接:{}", sessionId);
            log.info("用户：{}关闭连接！", userId);
        });

        // 处理自定义的事件，与连接监听类似,event为事件名，PushMessage为参数实体类 添加监听类
        // 监听前端发送的事件消息推送事件
        socketIOServer.addListeners(eventListenner);
        log.info("消息推送服务启动完毕！");
        socketIOServer.start();
    }

    @Override
    public void stop() {

        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;

        }
        log.info("消息推送服务已关闭！");
    }
}
